package com.wedistudio.slideshare;

import java.util.Date;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.simpleframework.xml.Serializer;

import android.annotation.SuppressLint;

import com.wedistudio.android.framework.fetcher.URLBuilder;
import com.wedistudio.android.framework.fetcher.URLParams;
import com.wedistudio.android.framework.pool.PoolFactory;
import com.wedistudio.android.framework.service.ServiceException;
import com.wedistudio.slideshare.xml.SlideShareServiceError;

public class SlideshareUtils {

	public static String SOURCE = "slideshare";
	private static String API_URL_BASE = "https://www.slideshare.net/api/2/";
	private static String API_KEY = "E6F5XDlR";
	private static String SHARED_SECRET = "cXSRZ8E0";

	@SuppressWarnings("deprecation")
	@SuppressLint("DefaultLocale")
	private static void addCredentials(URLParams params) {
		Date now = new Date();
		String ts = Long.toString(now.getTime() / 1000);
		String hash = new String(Hex.encodeHex(DigestUtils.sha(SHARED_SECRET
				+ ts))).toLowerCase();
		params.addParam("ts", ts);
		params.addParam("hash", hash);
		params.addParam("api_key", API_KEY);
	}

	public static URLParams buildURLParams(String action) {
		URLParams params = URLParams.create(URLBuilder.create(API_URL_BASE
				+ action));
		addCredentials(params);
		return params;
	}

	public static void checkResponse(String xml) {
		Serializer serializer = null;
		String message = null;
		try {
			serializer = PoolFactory.get(Serializer.class);

			SlideShareServiceError error = serializer.read(
					SlideShareServiceError.class, xml);

			message = error.Message.message;
		} catch (Throwable e) {
		} finally {
			PoolFactory.release(serializer, Serializer.class);
			if (message != null)
				throw new ServiceException(message);
		}
	}
}
